const mongoUtil = require("./mongo_util")
const collectionName = "goods"


function createGoods(goods, callback) {
    mongoUtil.getCollection(collectionName).then(collection => {
        collection.insertOne(goods, function (err, res) {
            callback(err, res)
        });
    })
}
function getAllGoods(goods, callback) {
    console.log(goods);
    const mmp = mongoUtil.getCollection(collectionName)
    mmp.then(collection => {
        collection.find({}).limit(Number(goods.pagesize)).skip((Number(goods.page) - 1) * Number(goods.pagesize)).sort({
            'orderlist.orderNo': -1
        }).toArray(function (err, result) { // 返回集合中所有数据
            if (result.length) {
                // console.log("gggggg");

                callback(null, result)
                new Error()
            } else {
                // console.log("hhhhhhhh");
                callback(err ? err : {
                    reason: "还没有商品"
                }, result)
            }
        });
    })
}
function updataGoods(goodslist, callback) {
    var whereStr = {
        'goodsId': Number(goodslist.goodsId),
        // 'goodsId':goodsId
    }
    console.log("==========", goodslist.goodsId, goodslist.goods);
    var updateStr = {
        $set: goodslist.goods

    };
    mongoUtil.getCollection(collectionName).then(collection => {
        collection.updateOne(whereStr, updateStr, function (err, res) {
            callback(err, res)
        });
    })
}
//商品下架Unsalable
function updataGoodsUnsalable(goodslist, callback) {
    var whereStr = {
        'goodsId': Number(goodslist.goodsId),
        // 'goodsId':goodsId
    }
    console.log("==========", goodslist.goodsId, goodslist.Unsalable);
    var updateStr = {
        $set: {'Unsalable':Number(goodslist.Unsalable)}

    };
    mongoUtil.getCollection(collectionName).then(collection => {
        collection.updateOne(whereStr, updateStr, function (err, res) {
            callback(err, res)
        });
    })
}
module.exports = {
    createGoods,
    updataGoods,
    updataGoodsUnsalable,
    getAllGoods
}